import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiResponseDto } from '../dto/response.dto';
import { ResponseCode } from '../types/response-code.enum';

@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, ApiResponseDto<T>> {
  intercept(context: ExecutionContext, next: CallHandler): Observable<ApiResponseDto<T>> {
    return next.handle().pipe(
      map(data => {
        try {
          // 如果已经是ApiResponseDto格式，直接返回
          if (data && typeof data === 'object' && 'code' in data && 'message' in data) {
            return data;
          }
          
          // 检查数据是否有效
          if (data === null || data === undefined) {
            return ApiResponseDto.success(null);
          }
          
          // 否则包装成标准格式
          return ApiResponseDto.success(data);
        } catch (error) {
          console.error('TransformInterceptor 错误:', error);
          return ApiResponseDto.error(ResponseCode.INTERNAL_SERVER_ERROR, '响应数据转换失败');
        }
      }),
    );
  }
} 